package com.dcr.controller;

import com.dcr.entity.PersonalCenter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class indexComtroller {

    @PostMapping("/login")
    @ResponseBody
    public String doLogin(@RequestBody Map<String,String> map){
        //依靠shiro的subject来实现登录的逻辑
        String username = map.get("username");
        String password = map.get("password");

        Subject subject = SecurityUtils.getSubject();
        //获取用户对象
        PersonalCenter currentPersonalCenter = (PersonalCenter) subject.getPrincipal();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            return "未知账户";
        } catch (IncorrectCredentialsException ice) {
            return "密码不正确";
        } catch (LockedAccountException lae) {
            return "账户已锁定";
        } catch (ExcessiveAttemptsException eae) {
            return "用户名或密码错误次数过多";
        } catch (AuthenticationException ae) {
            return "用户名或密码不正确！";
        }
        if(subject.isAuthenticated()){
            return "登录成功";
        }else {
            token.clear();
            return "登录失败";
        }
    }
//    /**
//     * 注销
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping(value = "/logout")
//    @ResponseBody
//    public RespEntity<String> logout(HttpServletRequest request) throws Exception {
//        RespEntity<String> resp = new RespEntity<>();
//        Subject currentUser = SecurityUtils.getSubject();
//        currentUser.logout();
//        resp.setHttpCode(HttpCode.Success);
//        resp.setMessage("注销成功");
//        return resp;
//    }
}
